package com.test.dao;


import com.test.entity.BookEntity;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import java.util.List;

public class BookDao {


    public List<BookEntity> query(int offset, int length) {
        Session session = null;
        List<BookEntity> list = null;
        try {
            Configuration conf = new Configuration().configure();
            SessionFactory sf = conf.buildSessionFactory();

            session = sf.openSession();
            String hql = "from BookEntity  ";
            Query query = session.createQuery(hql);
            query.setFirstResult(offset);
            query.setMaxResults(length);
            list = query.list();
        } catch (HibernateException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (session != null) {
                session.close();
            }
        }
        return list;
    }


    public List<BookEntity> query() {
        Session session = null;
        List<BookEntity> list = null;
        try {
            //实例化Configuration，这行代码默认加载hibernate.cfg.xml文件
            Configuration conf = new Configuration().configure();
            //以Configuration创建SessionFactory
            SessionFactory sf = conf.buildSessionFactory();
            //实例化Session
            session = sf.openSession();
            String hql = "from BookEntity  ";
            Query query = session.createQuery(hql);
            list = query.list();
        } catch (HibernateException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (session != null) {
                session.close();
            }
        }
        return list;
    }



    public int getAllRowCount() {
        List<BookEntity> list= query();
        return list.size();
    }
}
